package com.zh.demo.tabula;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * pdf文本提取器,根据关键字查找所在位置
 */
public class PDFTextStripperExtractor extends PDFTextStripper {

    @Getter
    @Setter
    private String keyText;   // 关键字文本

    @Getter
//    private List<TextPosition> keyTextPositionList = new ArrayList<>();  // 关键字文本位置
    // 存储关键词的坐标信息（x, y）
    private List<Float> keywordPositions = new ArrayList<>();

    /**
     * Instantiate a new PDFTextStripper object.
     *
     * @throws IOException If there is an error loading the properties.
     */
    public PDFTextStripperExtractor() throws IOException {
        super();
    }


    @Override
    protected void writeString(String text, List<TextPosition> textPositions) throws IOException {
        // 遍历文本片段，拼接字符并匹配关键词
        StringBuilder currentText = new StringBuilder();
        List<TextPosition> currentPositions = new ArrayList<>();

        for (TextPosition pos : textPositions) {
            String charStr = pos.getUnicode();
            currentText.append(charStr);
            currentPositions.add(pos);

            // 匹配到关键词时，记录其坐标（取第一个字符的x和基线y坐标）
            if (currentText.toString().contains(keyText)) {
                int startIndex = currentText.toString().indexOf(keyText);
//                int endIndex = startIndex + keyText.length();
                // 取关键词第一个字符的位置作为起始坐标
                TextPosition firstPos = currentPositions.get(startIndex);
                float x = firstPos.getX();
                float y = firstPos.getY(); // 基线y坐标（PDF原点在左下角，y轴向上）
//                keywordPositions.add(new float[]{x, y});
                keywordPositions.add(y);

                // 清空缓存，避免重复匹配
                currentText.setLength(0);
                currentPositions.clear();
            }
        }
    }



}
